package com.jz.community.moduleothers.scan.ui;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.jz.community.basecomm.base.BaseMvpFragment;
import com.jz.community.basecomm.bean.baseCardInfo.BaseCardInfo;
import com.jz.community.basecomm.mvp.BaseMvpPresenter;
import com.jz.community.basecomm.routerUtils.RouterCommonUtils;
import com.jz.community.basecomm.routerUtils.RouterIntentConstant;
import com.jz.community.basecomm.task.ITaskCallbackListener;
import com.jz.community.basecomm.utils.BaseSpUtils;
import com.jz.community.basecomm.utils.BaseUserUtils;
import com.jz.community.basecomm.utils.Preconditions;
import com.jz.community.basecomm.utils.RxImageTool;
import com.jz.community.basecomm.utils.SHelper;
import com.jz.community.basecomm.utils.rxbus.RxBus;
import com.jz.community.basecomm.utils.rxbus.eventType.ToLoginEvent;
import com.jz.community.commview.callback.EmptyCallback;
import com.jz.community.commview.callback.ErrorCallback;
import com.jz.community.commview.callback.LoginCallback;
import com.jz.community.commview.utils.TriangleDrawable;
import com.jz.community.commview.view.MSlideBottomLayout;
import com.jz.community.moduleothers.R;
import com.jz.community.moduleothers.R2;
import com.jz.community.moduleothers.scan.adapter.HomeQrCardAdapter;
import com.jz.community.moduleothers.scan.bean.ScanCardInfo;
import com.jz.community.moduleothers.scan.task.GetRefreshScanCodeTask;
import com.jz.community.moduleothers.scan.task.ScanCardTask;
import com.kingja.loadsir.callback.Callback;
import com.kingja.loadsir.core.LoadService;
import com.kingja.loadsir.core.LoadSir;
import com.zyyoona7.popup.EasyPopup;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import cn.bingoogolapple.qrcode.zxing.QRCodeEncoder;
import io.reactivex.Flowable;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Admin on 2018/3/26 0026.
 */
@Route(path = RouterIntentConstant.MODULE_OTHERS_HOME)
public class QRHomeFragment extends BaseMvpFragment {

    @BindView(R2.id.home_qr_title)
    TextView homeQrTitle;
    @BindView(R2.id.home_qr_toolbar)
    Toolbar homeQrToolbar;
    @BindView(R2.id.iv_home_qr_icon)
    ImageView ivHomeQrIcon;
    @BindView(R2.id.tv_home_qr_name)
    TextView tvHomeQrName;
    @BindView(R2.id.rl_home_qr_info)
    RelativeLayout rlHomeQrInfo;
    @BindView(R2.id.v_home_qr_line)
    View vHomeQrLine;
    @BindView(R2.id.iv_home_qr_barcode)
    ImageView ivHomeQrBarcode;
    @BindView(R2.id.tv_home_qr_numcode)
    TextView tvHomeQrNumcode;
    @BindView(R2.id.iv_home_qr_qrcode)
    ImageView ivHomeQrQrcode;
    @BindView(R2.id.home_qr_parent)
    RelativeLayout homeQrParent;
    @BindView(R2.id.slideLayout)
    MSlideBottomLayout slideLayout;
    @BindView(R2.id.tv_home_qr_qiehuan)
    TextView tvHomeQrQiehuan;
    @BindView(R2.id.iv_home_qr_qiehuan)
    ImageView ivHomeQrQiehuan;
    @BindView(R2.id.rv_home_qr_cardlist)
    RecyclerView rvHomeQrCardlist;
    @BindView(R2.id.home_qr_menu)
    ImageView homeQrMenu;
    @BindView(R2.id.scan_layout)
    RelativeLayout scan_layout;
    @BindView(R2.id.iv_home_qr_shuxin)
    ImageView ivHomeQrShuxin;
    @BindView(R2.id.tv_home_qr_shuxin_t1)
    TextView tvHomeQrShuxinT1;
    @BindView(R2.id.tv_home_qr_shuxin_t2)
    TextView tvHomeQrShuxinT2;
    @BindView(R2.id.rl_home_qr_refresh)
    RelativeLayout rl_home_qr_refresh;
    private EasyPopup moneyDetailPop;

    private LoadService loadService;
    private Observable<ToLoginEvent> toLoginRxBusObser;
    private String paymentNo;
    private String cardId;
    private int cardType;
    private HomeQrCardAdapter homeQrCardAdapter;
    private Disposable intervalInterval;

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.module_others_fragment_home_qr;
    }

    public static QRHomeFragment newInstance(String cardno, int cardType, String cardId) {
        QRHomeFragment orderFragment = new QRHomeFragment();
        Bundle bundle = new Bundle();
        bundle.putString("cardno", cardno);
        bundle.putString("cardId", cardId);
        bundle.putInt("cardType", cardType);
        orderFragment.setArguments(bundle);
        return orderFragment;
    }

    @Override
    protected void initLazy(@Nullable Bundle savedInstanceState) {
        homeQrTitle.setText("卡片二维码");
        if (BaseUserUtils.getIsLogin(getActivity())) {
            loadService.showSuccess();
            initQRData();
            toCardFrom();
            handleCardTypeState();
            initPop();
        } else {
            loadService.showCallback(LoginCallback.class);
        }
    }

    @Override
    protected void initVisible() {
        super.initVisible();
        setImmersionBar(homeQrToolbar);
    }

    @Override
    protected void initInvisible() {
        super.initInvisible();
        dispose();
    }

    @Override
    protected void initDatas() {
        loadService = LoadSir.getDefault().register(homeQrParent, (Callback.OnReloadListener) v -> {
            if (loadService.getCurrentCallback() == ErrorCallback.class) {
                initQRData();
            }
        });

        loadService.setCallBack(EmptyCallback.class, (context, view) -> {
            TextView mTvEmpty = view.findViewById(R.id.empty_tv);
            mTvEmpty.setText("暂无二维码！");
        });

        loadService.setCallBack(LoginCallback.class, (context, view) -> {
            TextView mTvLogin = view.findViewById(R.id.empty_login_btn);
            mTvLogin.setOnClickListener(v -> RouterCommonUtils.startNoParameterActivity(RouterIntentConstant.MODULE_AUTHORIZATION_LOGIN));
        });
    }

    @Override
    protected void initView() {
        registerLoginByRxBus();
    }

    @Override
    protected void addListener() {
        tvHomeQrNumcode.setOnClickListener(view -> {
            Intent intent = new Intent(getActivity(), QRShowActivity.class);
            intent.putExtra("qr", paymentNo);
            startActivity(intent);
        });

        ivHomeQrBarcode.setOnClickListener(view -> {
            Intent intent = new Intent(getActivity(), QRShowActivity.class);
            intent.putExtra("qr", paymentNo);
            startActivity(intent);
        });

        scan_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                slideLayout.switchVisible();
                SHelper.gone(scan_layout);
            }
        });

        slideLayout.setSlideListener(isTop -> {
            if (isTop) {
                SHelper.gone(scan_layout);
                tvHomeQrQiehuan.setText("切换卡片");
                scan_layout.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.transparent));
            } else {
                SHelper.vis(scan_layout);
                tvHomeQrQiehuan.setText("收起卡片");
                scan_layout.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.transparent_26));
            }
        });

        ivHomeQrQiehuan.setOnClickListener(view -> slideLayout.switchVisible());

        homeQrMenu.setOnClickListener(view -> {
            if (BaseUserUtils.showIsLoginDialog(getActivity())) {
                if (null != moneyDetailPop && moneyDetailPop.isShowing()) {
                    moneyDetailPop.dismiss();
                } else {
                    showPop(view);
                }
            }
        });
        ivHomeQrQrcode.setOnClickListener(v -> {
            if (cardType == 2) {
                refreshScanCode("1");
            } else {
                refreshScanCode("0");
            }
            handleClickRefreshScanTv();
        });
    }

    /**
     * 卡包、交易记录弹框
     *
     * @param view
     */
    public void showMoneyDetailPop(View view) {
        if (BaseUserUtils.showIsLoginDialog(getActivity())) {
            if (null != moneyDetailPop && moneyDetailPop.isShowing()) {
                moneyDetailPop.dismiss();
            } else {
                showPop(view);
            }
        }
    }

    /**
     * 定时60s刷新自营卡二维码
     * <p>
     * 0-E卡 1-其他卡劵
     */
    @SuppressLint("CheckResult")
    public void intervalRefreshScanCode() {
        final long codeTimes = 60;
        intervalInterval = Flowable.interval(codeTimes, TimeUnit.SECONDS).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(@NonNull Long aLong) throws Exception {
                        if (cardType == 2) {
                            refreshScanCode("1");
                        } else {
                            refreshScanCode("0");
                        }
                        handleClickRefreshScanTv();
                    }
                });
    }

    /**
     * 动态刷新二维码
     */
    private void refreshScanCode(String mark) {
        new GetRefreshScanCodeTask(getActivity(), new ITaskCallbackListener() {
            @Override
            public void doTaskComplete(Object o) {
                BaseCardInfo baseCardInfo = (BaseCardInfo) o;
                if (!Preconditions.isNullOrEmpty(baseCardInfo)) {
                    paymentNo = baseCardInfo.getCode();
                    makeScanEncode(paymentNo);
                    showScanCodeTv(paymentNo);
                    handleShowRefreshScanTv();
                }
            }
        }).execute(cardId, mark);
    }

    /**
     * 显示卡号
     *
     * @param paymentNo
     */
    private void showScanCodeTv(String paymentNo) {
        tvHomeQrNumcode.setText(paymentNo.substring(0, 4) + "******" + "查看数字");
    }

    /**
     * 处理点击刷新Tv
     */
    private void handleClickRefreshScanTv() {
        new Handler().postDelayed(() -> {
            tvHomeQrShuxinT1.setText("请点击二维码");
            tvHomeQrShuxinT2.setText("刷新");
            SHelper.vis(tvHomeQrShuxinT1, tvHomeQrShuxinT2);
            ivHomeQrShuxin.setImageResource(R.mipmap.shuaxin);
        }, 5000);
    }

    /**
     * 处理刷新后Tv
     */
    private void handleShowRefreshScanTv() {
        tvHomeQrShuxinT1.setText("已刷新");
        tvHomeQrShuxinT2.setVisibility(View.GONE);
        ivHomeQrShuxin.setImageResource(R.mipmap.yishuaxin);
    }

    private void showPop(View view) {
        moneyDetailPop.showAsDropDown(view, 0, SHelper.dp2px(getActivity(), 10));
    }

    private void initPop() {
        moneyDetailPop = EasyPopup.create()
                .setContentView(getActivity(), R.layout.module_others_pop_money_detail_layout)
                .setAnimationStyle(R.style.RightTop2PopAnim)
                //是否允许点击PopupWindow之外的地方消失
                .setFocusAndOutsideEnable(true)
                .setOnViewListener(view -> {
                    View arrowView = view.findViewById(R.id.pop_money_exchange_arrow);
                    arrowView.setBackground(new TriangleDrawable(TriangleDrawable.TOP, Color.parseColor("#FFFFFF")));

                    RelativeLayout exchange_ll = view.findViewById(R.id.pop_money_exchange_rl);
                    RelativeLayout purchase_ll = view.findViewById(R.id.pop_money_purchase_rl);

                    exchange_ll.setOnClickListener(v -> {
                        //交易明细
                        if (BaseSpUtils.getInstance().getIsLogin(getActivity())) {
                            RouterCommonUtils.startNoParameterActivity(RouterIntentConstant.CARD_MONEY_HISTORY);
                        } else {
                            BaseUserUtils.showIsLoginDialog(getActivity());
                        }
                        moneyDetailPop.dismiss();
                    });

                    purchase_ll.setOnClickListener(v -> {
                        //我的卡包
                        if (BaseSpUtils.getInstance().getIsLogin(getActivity())) {
                            RouterCommonUtils.startNoParameterActivity(RouterIntentConstant.MY_CARD);
                        } else {
                            BaseUserUtils.showIsLoginDialog(getActivity());
                        }
                        moneyDetailPop.dismiss();
                    });
                })
                .apply();
    }

    /**
     * 卡片来源
     */
    private void toCardFrom() {
        if (!Preconditions.isNullOrEmpty(getArguments())) {
            SHelper.gone(homeQrToolbar);
            paymentNo = getArguments().getString("cardno");
            cardId = getArguments().getString("cardId");
            cardType = getArguments().getInt("cardType");
            makeScanEncode(paymentNo);
            showScanCodeTv(paymentNo);
        } else {
            SHelper.vis(homeQrToolbar);
        }
    }

    /**
     * 登录处理
     */
    @SuppressLint("CheckResult")
    private void registerLoginByRxBus() {
        toLoginRxBusObser = RxBus.getInstance().register(ToLoginEvent.toLoginRxBusTag, ToLoginEvent.class);
        toLoginRxBusObser.subscribe(toLoginEvent -> {
            handleData(toLoginEvent);
        }, throwable -> {
        });
    }

    private void handleData(ToLoginEvent toLoginEvent) {
        if (toLoginEvent.isToPwdLogin() || toLoginEvent.isToWeChatLogin()) {
            initQRData();
        } else {
            loadService.showCallback(LoginCallback.class);
        }
    }

    private void loadScanInfo(ScanCardInfo scanCardInfo) {
        BaseCardInfo baseCardInfo = scanCardInfo.get_embedded().getContent().get(0);
        if (!Preconditions.isNullOrEmpty(baseCardInfo.getCardno())) {
            paymentNo = baseCardInfo.getCardno();
            cardType = baseCardInfo.getCardtype();
            cardId = baseCardInfo.getId();
            makeScanEncode(baseCardInfo.getCardno());
            showScanCodeTv(baseCardInfo.getCardno());
            loadService.showSuccess();
            handleCardAdapter(scanCardInfo);
        } else {
            loadService.showCallback(EmptyCallback.class);
        }
    }

    private void initQRData() {
        new ScanCardTask(getActivity(), o -> {
            ScanCardInfo baseInfo = (ScanCardInfo) o;
            if (!Preconditions.isNullOrEmpty(baseInfo) && !Preconditions.isNullOrEmpty(baseInfo.get_embedded().getContent())) {
                SHelper.vis(rl_home_qr_refresh);
                setScanLayoutEnabled(true);
                loadScanInfo(baseInfo);
            } else {
                SHelper.gone(rl_home_qr_refresh);
                setScanLayoutEnabled(false);
            }
        }).execute("2");
    }

    /**
     * 设置是否可点击
     *
     * @param isEnabled
     */
    private void setScanLayoutEnabled(boolean isEnabled) {
        slideLayout.setEnabled(isEnabled);
        ivHomeQrQiehuan.setEnabled(isEnabled);
        ivHomeQrBarcode.setEnabled(isEnabled);
        tvHomeQrNumcode.setEnabled(isEnabled);
    }

    /**
     * 处理自营卡、非自营卡状态
     */
    private void handleCardTypeState() {
        intervalRefreshScanCode();
    }

    @SuppressLint("CheckResult")
    private void makeScanEncode(final String qr) {
        Observable.just(qr)
                .map(new Function<String, Bitmap>() {
                    @Override
                    public Bitmap apply(String s) throws Exception {
                        Bitmap logoBitmap = BitmapFactory.decodeResource(QRHomeFragment.this.getActivity().getResources(), R.mipmap.ic_launcher);
                        return QRCodeEncoder.syncEncodeQRCode(s, 480, ContextCompat.getColor(getActivity(), R.color.balck), logoBitmap);
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe((Bitmap bm) -> {
                    ivHomeQrQrcode.setImageBitmap(bm);
                });

        Observable.just(qr)
                .map(new Function<String, Bitmap>() {
                    @Override
                    public Bitmap apply(String s) throws Exception {
                        return QRCodeEncoder.syncEncodeBarcode(s, SHelper.getScrrenW(getActivity()) - (SHelper.dp2px(getActivity(), 100)), RxImageTool.dp2px(70), 0);
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(bitmap -> ivHomeQrBarcode.setImageBitmap(bitmap));
    }

    private void handleCardAdapter(ScanCardInfo baseInfo) {
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        rvHomeQrCardlist.setLayoutManager(layoutManager);
        homeQrCardAdapter = new HomeQrCardAdapter(baseInfo.get_embedded().getContent());
        rvHomeQrCardlist.setAdapter(homeQrCardAdapter);
        rvHomeQrCardlist.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                if (parent.getChildAdapterPosition(view) != (homeQrCardAdapter.getData().size() - 1)) {
                    outRect.bottom = -40;
                }
            }
        });
        homeQrCardAdapter.setOnItemClickListener((adapter, view, position) -> {
            if (!Preconditions.isNullOrEmpty(homeQrCardAdapter.getData().get(position).getCardno())) {
                paymentNo = homeQrCardAdapter.getData().get(position).getCardno();
                cardType = homeQrCardAdapter.getData().get(position).getCardtype();
                cardId = homeQrCardAdapter.getData().get(position).getId();
                makeScanEncode(paymentNo);
                showScanCodeTv(paymentNo);
            }
            slideLayout.switchVisible();
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterLoginByRxBus();
    }

    @Override
    protected BaseMvpPresenter createPresenter() {
        return null;
    }

    private void unregisterLoginByRxBus() {
        RxBus.getInstance().unregister(ToLoginEvent.toLoginRxBusTag, toLoginRxBusObser);
    }

    private void dispose() {
        if (intervalInterval != null) {
            intervalInterval.dispose();
        }
    }

}
